import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from "@/views/home.vue";
import {validateToken} from "@/api/auth";

//路由列表
const routes = [
    {
        path: '/',
        name: 'login',
        component: Login
    },

    {
        path: '/home',
        name:'Home',
        component: Home
    }
]
//创建路由器
const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

//路由守卫
router.beforeEach(async (to, from, next) => {
    const accessToken = localStorage.getItem('accessToken');

    // 1. 白名单放行（无需认证的路径）
    const publicPaths = ['/'];

    if (publicPaths.includes(to.path)) {
        return next();
    }

    // 2. 无Token时跳转登录页
    if (!accessToken) {
        return next({
            path: '/',
        });
    }
    // 3. 验证Token有效性
    try {
        const isValid = await validateToken(accessToken);
        if(isValid.status === 200){
            console.log("token有效")
            console.log(isValid)
        }else{
            console.log("token无效")
            console.log(isValid)
            next('/');
        }

        next(); // 放行路由
    } catch (error) {
        console.error('Token验证失败:', error);
        localStorage.removeItem('accessToken');
        next('/?error=auth_failed');
    }
});

export default router
